package com.youtui.manager.session.impl;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.youtui.common.constant.SystemConstant;
import com.youtui.common.service.base.impl.BaseServiceImpl;
import com.youtui.common.util.JedisUtil;
import com.youtui.manager.session.SessionService;

@Service
/** redis的session管理类 */
public class RemoteSesessionServiceImpl extends BaseServiceImpl implements SessionService {

	@Override
	@SuppressWarnings("unchecked")
	public void setAttribute(HttpServletRequest request, HttpServletResponse response, String name,
			Serializable value) {
		Map<String, Serializable> map = null;
		map = (Map<String, Serializable>) jedisUtil.getObj(getSessionId(request, response));
		if (null == map) {
			map = new HashMap<String, Serializable>();
		}
		// 放入map
		map.put(name, value);
		// 保存redis,定义过期时间为10800秒
		jedisUtil.setObj(getSessionId(request, response), map, JedisUtil.seconds_m, true);
	}

	@SuppressWarnings("unchecked")
	@Override
	public Serializable getAttribute(HttpServletRequest request, HttpServletResponse response, String name) {
		Map<String, Serializable> map = (Map<String, Serializable>) jedisUtil.getObj(getSessionId(request, response));
		if (null != map) {
			return map.get(name);
		}
		return null;
	}

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response) {
		if (jedisUtil.exists(getSessionId(request, response))) {
			jedisUtil.del(getSessionId(request, response));
		}
		// 清理Cookie
		Cookie cookie = new Cookie(SystemConstant.SESSION_TYPE, "");
		cookie.setMaxAge(0);
		cookie.setPath("/");
		response.addCookie(cookie);
	}

	@Override
	public String getSessionId(HttpServletRequest request, HttpServletResponse response) {
		// 遍历所有Cookie
		Cookie[] cookies = request.getCookies();
		if (null != cookies && cookies.length > 0) {
			for (Cookie cookie : cookies) {
				if (SystemConstant.SESSION_TYPE.equals(cookie.getName())) {
					return cookie.getValue();
				}
			}
		}
		// 生成本地cookie

		String sessionId = "sessionId:" + request.getSession().getId();
		Cookie cookie = new Cookie(SystemConstant.SESSION_TYPE, sessionId);
		cookie.setMaxAge(Integer.MAX_VALUE);
		cookie.setPath("/");
		response.addCookie(cookie);
		return sessionId;
	}
}
